/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.hk.adv.service;

import com.thinkgem.jeesite.common.aliyuncs.AliyuncsUtil;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.service.ServiceException;
import com.thinkgem.jeesite.common.utils.ImgUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.hk.adv.dao.HkEnterpriseAdvDao;
import com.thinkgem.jeesite.modules.hk.adv.dao.HkEnterpriseProductDao;
import com.thinkgem.jeesite.modules.hk.adv.entity.HkAllAdv;
import com.thinkgem.jeesite.modules.hk.adv.entity.HkEnterpriseAdv;
import com.thinkgem.jeesite.modules.hk.adv.entity.HkEnterpriseProduct;
import com.thinkgem.jeesite.modules.hk.sys.entity.adv.HkCategory;
import com.thinkgem.jeesite.modules.hk.sys.entity.recommend.HkLoveSeeRecommend;
import com.thinkgem.jeesite.modules.hk.sys.entity.user.HkUser;
import com.thinkgem.jeesite.modules.hk.sys.service.adv.HkCategoryService;
import com.thinkgem.jeesite.modules.hk.sys.service.recommend.HkLoveSeeRecommendService;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.UriUtils;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

/**
 * 企业广告管理Service
 *
 * @author 罗天文
 * @version 2018-03-20
 */
@Service
@Transactional(readOnly = true)
public class HkEnterpriseAdvService extends CrudService<HkEnterpriseAdvDao, HkEnterpriseAdv> {
    @Autowired
    HkAllAdvService hkAllAdvService;
    @Autowired
    private HkLoveSeeRecommendService hkLoveSeeRecommendService;
    @Autowired
    private HkCategoryService hkCategoryService;
    @Autowired
    private HkEnterpriseProductDao hkEnterpriseProductDao;
    @Override
    public HkEnterpriseAdv get(String id) {
        HkEnterpriseAdv hkEnterpriseAdv = super.get(id);
        hkEnterpriseAdv.setHkEnterpriseProductList(hkEnterpriseProductDao.findList(new HkEnterpriseProduct(hkEnterpriseAdv)));
        return hkEnterpriseAdv;
    }

    @Override
    public List<HkEnterpriseAdv> findList(HkEnterpriseAdv hkEnterpriseAdv) {
        return super.findList(hkEnterpriseAdv);
    }

    @Override
    public Page<HkEnterpriseAdv> findPage(Page<HkEnterpriseAdv> page, HkEnterpriseAdv hkEnterpriseAdv) {
        return super.findPage(page, hkEnterpriseAdv);
    }

    @Transactional(readOnly = false)
    public void save(HkEnterpriseAdv hkEnterpriseAdv) {
        //hkEnterpriseAdv.setCategory(null);
		/*if(null!=hkEnterpriseAdv.getCategory()){
			hkEnterpriseAdv.setCategory(String.join(",", hkEnterpriseAdv.getCategorys()));
		}*/
        if (hkEnterpriseAdv.getNote() != null) {
            hkEnterpriseAdv.setNote(StringEscapeUtils.unescapeHtml4(hkEnterpriseAdv.getNote()));
        }
        hkEnterpriseAdv.setTag(null);
        if (null != hkEnterpriseAdv.getTags()) {
            hkEnterpriseAdv.setTag(String.join(",", hkEnterpriseAdv.getTags()));
        }
        String coverImgSrc = hkEnterpriseAdv.getCoverImgSrc();
        if (!coverImgSrc.contains(Global.getFileServer())) {
            coverImgSrc = (Global.getFileServer().trim() + hkEnterpriseAdv.getCoverImgSrc());
            Map<String, String> map = ImgUtils.getImgWidthHeight(hkEnterpriseAdv.getCoverImgSrc());
                hkEnterpriseAdv.setCoverImgWidth(map.get("width"));
                hkEnterpriseAdv.setCoverImgHeight(map.get("height"));
            }

            String officImgSrc = hkEnterpriseAdv.getOfficiaImgSrc();
            if (!officImgSrc.contains(Global.getFileServer())) {
                officImgSrc = (Global.getFileServer().trim() + hkEnterpriseAdv.getOfficiaImgSrc());
                Map<String, String> map = ImgUtils.getImgWidthHeight(hkEnterpriseAdv.getOfficiaImgSrc());
                hkEnterpriseAdv.setCoverOfficiaImgSrcWidth(map.get("width"));
                hkEnterpriseAdv.setCoverOfficiaImgSrcHeight(map.get("height"));
            }

            //企业视频
            if (StringUtils.isNotEmpty(hkEnterpriseAdv.getAimgSrc())) {

                String medisPath = Global.getUserfilesBaseDir() + hkEnterpriseAdv.getAimgSrc();
                try {
                    medisPath = UriUtils.decode(medisPath, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    throw new ServiceException("上传失败");
                }
                StringBuffer sb = new StringBuffer();
                HkCategory category;
                for (String c : hkEnterpriseAdv.getCategory().split(",")
                ) {
                    category = hkCategoryService.get(c);
                    sb.append(category.getName()).append(",");
            }
            String videoId = AliyuncsUtil.uploadVideo(hkEnterpriseAdv.getTitle(), medisPath, coverImgSrc, sb.toString());

            if (StringUtils.isEmpty(videoId)) {
                throw new ServiceException("上传失败");
            }
            hkEnterpriseAdv.setImgSrc(videoId);
        }

        //企业官方视频
        if (StringUtils.isNotEmpty(hkEnterpriseAdv.getAofficiaVideo())) {
            String officMediaPath = Global.getUserfilesBaseDir() + hkEnterpriseAdv.getAofficiaVideo();
            try {
                officMediaPath = UriUtils.decode(officMediaPath, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new ServiceException("官方视频上传失败");
            }
            StringBuffer sb = new StringBuffer();
            HkCategory category;
            for (String c : hkEnterpriseAdv.getCategory().split(",")
            ) {
                category = hkCategoryService.get(c);
                sb.append(category.getName()).append(",");
            }
            String officVideoId = AliyuncsUtil.uploadVideo(hkEnterpriseAdv.getOfficiaTitle(), officMediaPath, officImgSrc, sb.toString());

            if (StringUtils.isEmpty(officVideoId)) {
                throw new ServiceException("官方视频上传失败");
            }
            hkEnterpriseAdv.setOfficiaVideo(officVideoId);
        }

        super.save(hkEnterpriseAdv);

        deleteTag(hkEnterpriseAdv);
        insertTag(hkEnterpriseAdv);
        deleteCategory(hkEnterpriseAdv);
        insertCategory(hkEnterpriseAdv);
        if (hkEnterpriseAdv.getState().equals("1")) {
            insertAllAdv(hkEnterpriseAdv);
        }
        for (HkEnterpriseProduct hkEnterpriseProduct : hkEnterpriseAdv.getHkEnterpriseProductList()){
            if (hkEnterpriseProduct.getId() == null){
                continue;
            }
            if (HkEnterpriseProduct.DEL_FLAG_NORMAL.equals(hkEnterpriseProduct.getDelFlag())){
                if (StringUtils.isBlank(hkEnterpriseProduct.getId())){
                    hkEnterpriseProduct.setEnterpriseAdv(hkEnterpriseAdv);
                    hkEnterpriseProduct.preInsert();
                    hkEnterpriseProductDao.insert(hkEnterpriseProduct);
                }else{
                    hkEnterpriseProduct.preUpdate();
                    hkEnterpriseProductDao.update(hkEnterpriseProduct);
                }
            }else{
                hkEnterpriseProductDao.delete(hkEnterpriseProduct);
            }
        }
    }

    @Transactional(readOnly = false)
    @Override
    public void delete(HkEnterpriseAdv hkEnterpriseAdv) {
        super.delete(hkEnterpriseAdv);
        hkEnterpriseProductDao.delete(new HkEnterpriseProduct(hkEnterpriseAdv));
    }

    /**
     * 删除标签
     *
     * @param hkEnterpriseAdv
     * @return
     */
    private void deleteCategory(HkEnterpriseAdv hkEnterpriseAdv) {
        super.dao.deleteCategory(hkEnterpriseAdv);
    }

    /**
     * 增加标签
     *
     * @param hkEnterpriseAdv
     * @return
     */
    private void insertCategory(HkEnterpriseAdv hkEnterpriseAdv) {
        super.dao.insertCategory(hkEnterpriseAdv);
    }

    //同步数据
    private void insertAllAdv(HkEnterpriseAdv hkEnterpriseAdv) {
        String sourceId = hkEnterpriseAdv.getId();
        HkAllAdv hkAllAdvOld = hkAllAdvService.getBySourceId(sourceId);
        if (null == hkAllAdvOld) {
            HkAllAdv hkAllAdv = new HkAllAdv();
            BeanUtils.copyProperties(hkEnterpriseAdv, hkAllAdv);
            hkAllAdv.setId(null);
            hkAllAdv.setSourceId(hkEnterpriseAdv.getId());
            //类型  1自媒体 2企业广告3城市广告4传统文化s
            hkAllAdv.setType("2");
            hkAllAdvService.save(hkAllAdv);
        } else {
            HkAllAdv hkAllAdv = hkAllAdvOld;
            BeanUtils.copyProperties(hkEnterpriseAdv, hkAllAdv);
            hkAllAdv.setId(hkAllAdvOld.getId());
            hkAllAdvService.save(hkAllAdv);
        }

        hkAllAdvService.deleteTag(hkEnterpriseAdv.getId(), hkEnterpriseAdv.getTag());
        hkAllAdvService.insertTag(hkEnterpriseAdv.getId(), hkEnterpriseAdv.getTag());
        hkAllAdvService.deleteCategory(hkEnterpriseAdv.getId(), hkEnterpriseAdv.getCategory());
        hkAllAdvService.insertCategory(hkEnterpriseAdv.getId(), hkEnterpriseAdv.getCategory());
    }

    /**
     * 删除标签
     *
     * @param hkEnterpriseAdv
     * @return
     */
    private void deleteTag(HkEnterpriseAdv hkEnterpriseAdv) {
        super.dao.deleteTag(hkEnterpriseAdv);
    }

    /**
     * 增加标签
     *
     * @param hkEnterpriseAdv
     * @return
     */
    private void insertTag(HkEnterpriseAdv hkEnterpriseAdv) {
        //super.dao.insertTag(hkEnterpriseAdv);
    }

    @Transactional(readOnly = false)
    public void recommend(HkEnterpriseAdv hkEnterpriseAdv) {
        HkAllAdv hkAllAdv = hkAllAdvService.getBySourceId(hkEnterpriseAdv.getId());
        HkLoveSeeRecommend hkLoveSeeRecommend = new HkLoveSeeRecommend();
        BeanUtils.copyProperties(hkAllAdv, hkLoveSeeRecommend);
        hkLoveSeeRecommend.setId(null);
        HkUser hkUser = new HkUser();
        hkLoveSeeRecommend.setUser(hkUser);
        hkLoveSeeRecommendService.save(hkLoveSeeRecommend);
    }
}